# -*- coding: utf-8 -*-
"""
保温杯中性策略3期 | 邢不行 | 2023分享会
author: 邢不行
微信: xbx6660
"""
import numpy as np
import pandas as pd


def signal(*args):
    df = args[0]
    n = args[1]
    factor_name = args[2]
    df['bbi'] = (df['close'].rolling(n, min_periods=1).mean() + df['close'].rolling(2 * n, min_periods=1).mean() + \
                df['close'].rolling(4 * n, min_periods=1).mean()) / 3
    df['bbi_bias'] = df['close'] / df['bbi']
    df['route_1'] = 2 * (df['high'] - df['low']) + (df['open'] - df['close'])
    df['route_2'] = 2 * (df['high'] - df['low']) + (df['close'] - df['open'])
    df.loc[df['route_1'] > df['route_2'], '盘中最短路径'] = df['route_2']
    df.loc[df['route_1'] <= df['route_2'], '盘中最短路径'] = df['route_1']
    df['最短路径_标准化'] = df['盘中最短路径'] / df['open']
    df['流动溢价'] = df['quote_volume'] / df['最短路径_标准化']

    def apply_log(x):
        if isinstance(x, float):
            print('111111111111111111[')
            print(x)
            print(type(x))
            print(']111111111111111111')

            print('2222222222222222222[')
            print(np.log(x))
            print(']2222222222222222222')
            return x
        else:
            return x

    #df['流动溢价'] = pd.to_numeric(df['流动溢价'], errors='coerce')
    #df['流动溢价'] = df['流动溢价'].replace(None, 0.0)
    #df['流动溢价'] = df['流动溢价'].fillna(0.0)
    #df['流动溢价'] = df['流动溢价'].apply(lambda x: print(type(x)))
    #df['流动溢价'] = df['流动溢价'].apply(lambda x: print(x))
    #df['流动溢价'] = df['流动溢价'].apply(apply_log)
    df['流动溢价'] = np.log(df['流动溢价'])
    df[factor_name] = df['流动溢价'].rolling(n, min_periods=2).std() * df['bbi_bias']

    del df['route_1']
    del df['route_2']
    del df['盘中最短路径']
    del df['最短路径_标准化']
    del df['流动溢价']

    return df

